<template>
  <div class="admin-statistics-view" style="margin-top: 800px">
    <div class="statistics-header">
      <h1 class="page-title">销售统计</h1>
      <div class="header-controls">
        <a-segmented v-model:value="period" :options="periodOptions" @change="handlePeriodChange" />
        <a-date-picker v-model:value="dateRange" picker="date" placeholder="选择日期" @change="handleDateChange" />
      </div>
    </div>

    <!-- 数据概览卡片 -->
    <div class="stats-cards">
      <a-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon revenue">
            <DollarOutlined />
          </div>
          <div class="stat-info">
            <div class="stat-value">¥{{ formatNumber(totalRevenue) }}</div>
            <div class="stat-label">总销售额</div>
            <div class="stat-change" :class="revenueChange >= 0 ? 'positive' : 'negative'">
              {{ revenueChange >= 0 ? '+' : '' }}{{ revenueChange }}%
            </div>
          </div>
        </div>
      </a-card>

      <a-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon orders">
            <ShoppingOutlined />
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ formatNumber(totalOrders) }}</div>
            <div class="stat-label">订单数量</div>
            <div class="stat-change" :class="orderChange >= 0 ? 'positive' : 'negative'">
              {{ orderChange >= 0 ? '+' : '' }}{{ orderChange }}%
            </div>
          </div>
        </div>
      </a-card>

      <a-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon customers">
            <UserOutlined />
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ formatNumber(newCustomers) }}</div>
            <div class="stat-label">新增客户</div>
            <div class="stat-change" :class="customerChange >= 0 ? 'positive' : 'negative'">
              {{ customerChange >= 0 ? '+' : '' }}{{ customerChange }}%
            </div>
          </div>
        </div>
      </a-card>

      <a-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon products">
            <GiftOutlined />
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ formatNumber(totalProducts) }}</div>
            <div class="stat-label">商品销量</div>
            <div class="stat-change" :class="productChange >= 0 ? 'positive' : 'negative'">
              {{ productChange >= 0 ? '+' : '' }}{{ productChange }}%
            </div>
          </div>
        </div>
      </a-card>
    </div>

    <!-- 图表区域 -->
    <div class="charts-section">
      <div class="chart-row">
        <a-card title="销售趋势" class="chart-card">
          <div class="chart-container">
            <v-chart class="chart" :option="salesTrendOption" />
          </div>
        </a-card>

        <a-card title="商品分类销售" class="chart-card">
          <div class="chart-container">
            <v-chart class="chart" :option="categorySalesOption" />
          </div>
        </a-card>
      </div>

      <a-card title="热销商品排行" class="chart-card full-width">
        <a-table :columns="productColumns" :data-source="topProducts" :pagination="false" size="small">
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'rank'">
              <div class="rank-badge" :class="`rank-${record.rank}`">{{ record.rank }}</div>
            </template>
            <template v-else-if="column.key === 'image'">
              <img :src="record.image" :alt="record.name" class="product-image" />
            </template>
            <template v-else-if="column.key === 'sales'">
              <span class="sales-count">{{ record.sales }}件</span>
            </template>
            <template v-else-if="column.key === 'revenue'">
              <span class="revenue-amount">¥{{ record.revenue }}</span>
            </template>
          </template>
        </a-table>
      </a-card>
    </div>

    <!-- 详细数据表格 -->
    <a-card title="销售明细" class="detail-table">
      <a-table :columns="detailColumns" :data-source="salesDetails" :pagination="{ pageSize: 10 }">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">{{ record.status }}</a-tag>
          </template>
          <template v-else-if="column.key === 'amount'">
            <span class="amount-text">¥{{ record.amount }}</span>
          </template>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import {
  DollarOutlined,
  ShoppingOutlined,
  UserOutlined,
  GiftOutlined
} from '@ant-design/icons-vue'

// 注册 ECharts 组件
use([
  CanvasRenderer,
  LineChart,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

const period = ref('日')
const dateRange = ref(null)

// 统计数据
const totalRevenue = ref(128560)
const totalOrders = ref(1234)
const newCustomers = ref(856)
const totalProducts = ref(2847)

const revenueChange = ref(12.5)
const orderChange = ref(8.3)
const customerChange = ref(15.2)
const productChange = ref(-2.1)

const periodOptions = [
  { label: '今日', value: '日' },
  { label: '本周', value: '周' },
  { label: '本月', value: '月' },
  { label: '本年', value: '年' }
]

// 销售趋势数据
const salesTrendData = ref([
  { date: '01-01', revenue: 12000, orders: 45 },
  { date: '01-02', revenue: 13500, orders: 52 },
  { date: '01-03', revenue: 11800, orders: 48 },
  { date: '01-04', revenue: 14200, orders: 55 },
  { date: '01-05', revenue: 15600, orders: 62 },
  { date: '01-06', revenue: 13800, orders: 51 },
  { date: '01-07', revenue: 16200, orders: 65 },
  { date: '01-08', revenue: 14500, orders: 58 },
  { date: '01-09', revenue: 17800, orders: 72 },
  { date: '01-10', revenue: 16500, orders: 68 },
  { date: '01-11', revenue: 18900, orders: 75 },
  { date: '01-12', revenue: 17200, orders: 70 },
  { date: '01-13', revenue: 20100, orders: 82 },
  { date: '01-14', revenue: 18500, orders: 76 },
  { date: '01-15', revenue: 21500, orders: 88 }
])

// 商品分类销售数据
const categorySalesData = ref([
  { name: '护肤精华', value: 45600, percentage: 35.5 },
  { name: '面霜乳液', value: 32400, percentage: 25.2 },
  { name: '洁面卸妆', value: 21800, percentage: 17.0 },
  { name: '面膜护理', value: 15600, percentage: 12.1 },
  { name: '防晒隔离', value: 12800, percentage: 10.0 },
  { name: '其他', value: 360, percentage: 0.2 }
])

// 销售趋势图表配置
const salesTrendOption = computed(() => ({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross',
      label: {
        backgroundColor: '#6a7985'
      }
    }
  },
  legend: {
    data: ['销售额', '订单数'],
    textStyle: {
      color: '#666'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: [
    {
      type: 'category',
      boundaryGap: false,
      data: salesTrendData.value.map(item => item.date),
      axisLine: {
        lineStyle: {
          color: '#ddd'
        }
      },
      axisLabel: {
        color: '#666'
      }
    }
  ],
  yAxis: [
    {
      type: 'value',
      name: '销售额 (元)',
      axisLine: {
        lineStyle: {
          color: '#ddd'
        }
      },
      axisLabel: {
        color: '#666',
        formatter: '{value}'
      },
      splitLine: {
        lineStyle: {
          color: '#f0f0f0'
        }
      }
    },
    {
      type: 'value',
      name: '订单数',
      axisLine: {
        lineStyle: {
          color: '#ddd'
        }
      },
      axisLabel: {
        color: '#666'
      },
      splitLine: {
        show: false
      }
    }
  ],
  series: [
    {
      name: '销售额',
      type: 'line',
      stack: 'Total',
      areaStyle: {
        opacity: 0.1,
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: '#667eea' },
            { offset: 1, color: 'rgba(102, 126, 234, 0.1)' }
          ]
        }
      },
      emphasis: {
        focus: 'series'
      },
      data: salesTrendData.value.map(item => item.revenue),
      itemStyle: {
        color: '#667eea'
      },
      lineStyle: {
        color: '#667eea',
        width: 3
      },
      smooth: true
    },
    {
      name: '订单数',
      type: 'line',
      yAxisIndex: 1,
      emphasis: {
        focus: 'series'
      },
      data: salesTrendData.value.map(item => item.orders),
      itemStyle: {
        color: '#f093fb'
      },
      lineStyle: {
        color: '#f093fb',
        width: 3
      },
      smooth: true
    }
  ]
}))

// 商品分类销售饼图配置
const categorySalesOption = computed(() => ({
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)'
  },
  legend: {
    orient: 'vertical',
    left: 'left',
    textStyle: {
      color: '#666'
    }
  },
  series: [
    {
      name: '销售占比',
      type: 'pie',
      radius: ['40%', '70%'],
      center: ['60%', '50%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: '18',
          fontWeight: 'bold',
          color: '#333'
        }
      },
      labelLine: {
        show: false
      },
      data: categorySalesData.value.map(item => ({
        name: item.name,
        value: item.value,
        itemStyle: {
          color: getCategoryColor(item.name)
        }
      }))
    }
  ]
}))

// 获取分类颜色
const getCategoryColor = (name: string) => {
  const colorMap: Record<string, string> = {
    '护肤精华': '#667eea',
    '面霜乳液': '#f093fb',
    '洁面卸妆': '#4facfe',
    '面膜护理': '#43e97b',
    '防晒隔离': '#fa709a',
    '其他': '#ffecd2'
  }
  return colorMap[name] || '#d9d9d9'
}

// 热销商品表格列定义
const productColumns = [
  {
    title: '排名',
    dataIndex: 'rank',
    key: 'rank',
    width: 80,
  },
  {
    title: '商品图片',
    dataIndex: 'image',
    key: 'image',
    width: 80,
  },
  {
    title: '商品名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '销量',
    dataIndex: 'sales',
    key: 'sales',
    width: 100,
  },
  {
    title: '销售额',
    dataIndex: 'revenue',
    key: 'revenue',
    width: 120,
  },
]

// 热销商品数据
const topProducts = ref([
  {
    key: '1',
    rank: 1,
    image: 'https://via.placeholder.com/60x60/667eea/ffffff?text=商品1',
    name: '兰蔻小黑瓶精华液',
    sales: 156,
    revenue: '140,400'
  },
  {
    key: '2',
    rank: 2,
    image: 'https://via.placeholder.com/60x60/74b9ff/ffffff?text=商品2',
    name: '雅诗兰黛小棕瓶',
    sales: 142,
    revenue: '127,800'
  },
  {
    key: '3',
    rank: 3,
    image: 'https://via.placeholder.com/60x60/55a3ff/ffffff?text=商品3',
    name: 'SK-II神仙水',
    sales: 128,
    revenue: '115,200'
  },
  {
    key: '4',
    rank: 4,
    image: 'https://via.placeholder.com/60x60/36cfc9/ffffff?text=商品4',
    name: '资生堂红腰子',
    sales: 115,
    revenue: '103,500'
  },
  {
    key: '5',
    rank: 5,
    image: 'https://via.placeholder.com/60x60/73d13d/ffffff?text=商品5',
    name: '赫莲娜绿宝瓶',
    sales: 98,
    revenue: '88,200'
  }
])

// 销售明细表格列定义
const detailColumns = [
  {
    title: '订单号',
    dataIndex: 'orderId',
    key: 'orderId',
  },
  {
    title: '客户',
    dataIndex: 'customer',
    key: 'customer',
  },
  {
    title: '商品',
    dataIndex: 'product',
    key: 'product',
  },
  {
    title: '数量',
    dataIndex: 'quantity',
    key: 'quantity',
  },
  {
    title: '金额',
    dataIndex: 'amount',
    key: 'amount',
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
  },
  {
    title: '时间',
    dataIndex: 'time',
    key: 'time',
  },
]

// 销售明细数据
const salesDetails = ref([
  {
    key: '1',
    orderId: 'ORD202401001',
    customer: '张三',
    product: '兰蔻小黑瓶精华液',
    quantity: 2,
    amount: '1,798',
    status: '已完成',
    time: '2024-01-15 14:30'
  },
  {
    key: '2',
    orderId: 'ORD202401002',
    customer: '李四',
    product: '雅诗兰黛小棕瓶',
    quantity: 1,
    amount: '899',
    status: '已发货',
    time: '2024-01-15 15:20'
  },
  {
    key: '3',
    orderId: 'ORD202401003',
    customer: '王五',
    product: 'SK-II神仙水',
    quantity: 3,
    amount: '2,697',
    status: '已完成',
    time: '2024-01-15 16:10'
  },
  {
    key: '4',
    orderId: 'ORD202401004',
    customer: '赵六',
    product: '资生堂红腰子',
    quantity: 1,
    amount: '899',
    status: '待发货',
    time: '2024-01-15 17:05'
  },
  {
    key: '5',
    orderId: 'ORD202401005',
    customer: '钱七',
    product: '赫莲娜绿宝瓶',
    quantity: 2,
    amount: '1,798',
    status: '已完成',
    time: '2024-01-15 18:30'
  }
])

// 工具函数
const formatNumber = (num: number) => {
  return num.toLocaleString()
}

const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    '已完成': 'green',
    '已发货': 'blue',
    '待发货': 'orange',
    '已取消': 'red'
  }
  return colorMap[status] || 'default'
}

// 事件处理
const handlePeriodChange = (value: string) => {
  console.log('时间段变化:', value)
  // 这里可以根据时间段更新数据
}

const handleDateChange = (date: any) => {
  console.log('日期变化:', date)
  // 这里可以根据日期更新数据
}

onMounted(() => {
  console.log('统计页面已加载')
})
</script>

<style scoped>
.admin-statistics-view {
  padding: 16px;
  background: #f5f7fa;
  min-height: calc(100vh - 64px);
  width: 100%;
  max-width: 100%;
  margin: 0;
  overflow-y: auto;
}

.statistics-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  background: white;
  padding: 16px 20px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  flex-wrap: wrap;
  gap: 12px;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0;
}

.header-controls {
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 16px;
  margin-bottom: 16px;
}

.stat-card {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: none;
  min-height: 120px;
}

.stat-card :deep(.ant-card-body) {
  padding: 16px;
  height: 100%;
  display: flex;
  align-items: center;
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 12px;
  width: 100%;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: white;
  flex-shrink: 0;
}

.stat-icon.revenue {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.orders {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon.customers {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-icon.products {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-info {
  flex: 1;
  min-width: 0;
}

.stat-value {
  font-size: 24px;
  font-weight: 700;
  color: #1a1a1a;
  line-height: 1;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.stat-label {
  font-size: 13px;
  color: #666;
  margin-bottom: 6px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.stat-change {
  font-size: 11px;
  font-weight: 600;
  padding: 2px 6px;
  border-radius: 4px;
  display: inline-block;
  white-space: nowrap;
}

.stat-change.positive {
  background: #f6ffed;
  color: #52c41a;
}

.stat-change.negative {
  background: #fff2f0;
  color: #ff4d4f;
}

.charts-section {
  margin-bottom: 24px;
}

.chart-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 20px;
}

.chart-card {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: none;
}

.chart-card.full-width {
  grid-column: 1 / -1;
}

.chart-card :deep(.ant-card-head) {
  border-bottom: 1px solid #f0f0f0;
  padding: 0 24px;
}

.chart-card :deep(.ant-card-head-title) {
  font-size: 16px;
  font-weight: 600;
  color: #1a1a1a;
}

.chart-card :deep(.ant-card-body) {
  padding: 24px;
}

.chart-container {
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chart {
  width: 100%;
  height: 100%;
}

.rank-badge {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: 600;
  color: white;
}

.rank-1 {
  background: #ffd700;
}

.rank-2 {
  background: #c0c0c0;
}

.rank-3 {
  background: #cd7f32;
}

.rank-4, .rank-5 {
  background: #f0f0f0;
  color: #666;
}

.product-image {
  width: 40px;
  height: 40px;
  border-radius: 6px;
  object-fit: cover;
}

.sales-count {
  font-weight: 600;
  color: #1890ff;
}

.revenue-amount {
  font-weight: 600;
  color: #52c41a;
}

.detail-table {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: none;
}

.detail-table :deep(.ant-card-head) {
  border-bottom: 1px solid #f0f0f0;
  padding: 0 24px;
}

.detail-table :deep(.ant-card-head-title) {
  font-size: 16px;
  font-weight: 600;
  color: #1a1a1a;
}

.detail-table :deep(.ant-card-body) {
  padding: 24px;
}

.amount-text {
  font-weight: 600;
  color: #52c41a;
}

@media (max-width: 1200px) {
  .chart-row {
    grid-template-columns: 1fr;
  }

  .stats-cards {
    grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
    gap: 12px;
  }
}

@media (max-width: 768px) {
  .admin-statistics-view {
    padding: 12px;
  }

  .statistics-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
    padding: 12px 16px;
  }

  .header-controls {
    justify-content: space-between;
    gap: 8px;
  }

  .stats-cards {
    grid-template-columns: 1fr;
    gap: 12px;
  }

  .stat-content {
    gap: 10px;
  }

  .stat-icon {
    width: 45px;
    height: 45px;
    font-size: 18px;
  }

  .stat-value {
    font-size: 20px;
  }

  .chart-container {
    height: 200px;
  }
}

@media (max-width: 480px) {
  .admin-statistics-view {
    padding: 8px;
  }

  .statistics-header {
    padding: 10px 12px;
    margin-bottom: 12px;
  }

  .page-title {
    font-size: 18px;
  }

  .header-controls {
    flex-direction: column;
    gap: 8px;
  }

  .stat-card :deep(.ant-card-body) {
    padding: 12px;
  }

  .chart-card :deep(.ant-card-body) {
    padding: 12px;
  }

  .chart-container {
    height: 180px;
  }

  .stat-value {
    font-size: 18px;
  }

  .stat-label {
    font-size: 12px;
  }
}
</style>
